<template>
  <el-dialog
    v-loading="loading"
    append-to-body
    :title="title"
    :visible.sync="dialogVisible"
    width="800px"
    @close="result = false"
  >
    <div class="ele-table-tool ele-table-tool-default">
      <el-button
        icon="el-icon-plus"
        size="mini"
        type="primary"
        @click="handleAdd"
      >
        添加
      </el-button>
    </div>
    <el-table border :data="plants" stripe>
      <el-table-column align="center" label="编号" type="index" width="80" />
      <el-table-column align="center" label="作物名称" prop="crop.name" />
      <el-table-column align="center" label="种植年" prop="plant_year" />
      <el-table-column align="center" label="茬" prop="stubble" />
      <el-table-column align="center" label="状态" prop="autocare_mode">
        <template #default="{ row }">
          <el-tag v-if="row.autocare_mode" type="success">开启</el-tag>
          <el-tag v-else type="danger">关闭</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="160">
        <template #default="{ row }">
          <el-link icon="el-icon-edit" type="primary" @click="handleEdit(row)">
            修改
          </el-link>
          <el-link
            class="ml12"
            icon="el-icon-delete"
            type="danger"
            @click="handleDelete(row)"
          >
            删除
          </el-link>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
      append-to-body
      title="种植设置"
      :visible.sync="dialogFormVisible"
      width="1200px"
      @close="resetForm"
    >
      <el-form
        ref="mainForm"
        label-width="100px"
        :model="form"
        :rules="rules"
        size="medium"
      >
        <el-divider content-position="left">
          <b class="color-primary">基本参数设置</b>
        </el-divider>
        <el-row>
          <el-col :span="8">
            <el-form-item label="作物选择" prop="crop_id">
              <el-select v-model="form.crop_id" clearable filterable>
                <el-option
                  v-for="(item, index) in crops"
                  :key="index"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :inline="true" label="种植年" prop="plant_year">
              <el-date-picker
                v-model="form.plant_year"
                placeholder="选择年"
                type="year"
                value-format="yyyy"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="自动决策" prop="autocare">
              <el-switch
                v-model="form.autocare_mode"
                active-text="打开"
                :active-value="1"
                inactive-text="关闭"
                :inactive-value="0"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="当前茬" prop="stubble">
              <el-select v-model="form.stubble" clearable filterable>
                <el-option v-for="i in 3" :key="i" :label="i" :value="i" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :inline="true" label="当茬开始日" prop="started_at">
              <el-date-picker
                v-model="form.started_at"
                placeholder="选择日期"
                type="date"
                value-format="yyyy-MM-dd"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="决策暂停" prop="autopause">
              <el-switch
                v-model="form.autopause"
                active-text="打开"
                :active-value="1"
                inactive-text="关闭"
                :inactive-value="0"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider content-position="left">
          <b class="color-primary">生育期设置</b>
        </el-divider>
        <el-table border :data="form.cropGrowthes" size="small">
          <el-table-column align="center" label="名称" prop="name" width="160">
            <template #default="{ row }">
              <el-input
                v-model="row.stage_name"
                clearable
                placeholder="名称"
                size="small"
              />
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="起止时间"
            prop="max"
            width="380"
          >
            <template #default="{ row }">
              <el-date-picker
                v-model="row.daterange"
                end-placeholder="结束日期"
                range-separator="~"
                start-placeholder="开始日期"
                type="daterange"
                value-format="yyyy-MM-dd"
              />
            </template>
          </el-table-column>
          <el-table-column align="center" label="灌水上限" prop="max">
            <template #default="{ row }">
              <el-input
                v-model="row.wc_max"
                placeholder="灌水上限"
                size="small"
                type="number"
              >
                <template slot="append">%</template>
              </el-input>
            </template>
          </el-table-column>
          <el-table-column align="center" label="灌水下限" prop="min">
            <template #default="{ row }">
              <el-input
                v-model="row.wc_min"
                placeholder="灌水下限"
                size="small"
                type="number"
              >
                <template slot="append">%</template>
              </el-input>
            </template>
          </el-table-column>
          <el-table-column align="center" label="湿润层深度" prop="depth">
            <template #default="{ row }">
              <el-input
                v-model="row.soil_depth"
                placeholder="湿润层深度"
                size="small"
                type="number"
              >
                <template slot="append">mm</template>
              </el-input>
            </template>
          </el-table-column>
          <el-table-column align="center" label="作物系数" prop="kc_start">
            <template #default="{ row }">
              <el-input
                v-model="row.kc_start"
                clearable
                placeholder="作物系数"
                size="small"
                type="number"
              />
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="操作"
            prop="operate"
            width="100"
          >
            <template #header>
              <el-link size="mini" type="primary" @click="addRow">添加</el-link>
            </template>
            <template #default="{ row, $index }">
              <el-link type="danger" @click="deleteRow(row, $index)">
                删除
              </el-link>
            </template>
          </el-table-column>
        </el-table>
        <div class="h24"></div>
        <el-form-item>
          <el-button type="primary" @click="submit('mainForm')">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </el-dialog>
</template>

<script>
  import { getAll, getOne, addOne, updateOne } from '@/api/plant'
  import { getCrops } from '@/api/device'
  import { fieldId } from '@/utils/constant'
  export default {
    data() {
      return {
        dialogFormVisible: false,
        dialogVisible: false,
        title: '种植设置',
        loading: false,
        plants: [],
        crops: [],
        fieldId,
        form: {
          field_id: '',
          crop_id: '',
          plant_year: '',
          stubble: 1,
          started_at: '',
          autocare_mode: 0,
          autopause: 0,
          cropGrowthes: [],
        },
        rules: {
          crop_id: [{ required: true, message: '请选择作物', trigger: 'blur' }],
          plant_year: [
            { required: true, message: '请选择种植年', trigger: 'blur' },
          ],
          stubble: [
            { required: true, message: '请选择当前茬', trigger: 'blur' },
          ],
          started_at: [
            { required: true, message: '请选择当茬开始日', trigger: 'blur' },
          ],
        },
      }
    },
    methods: {
      async show() {
        this.getAll()
        this.getCrops()
        this.dialogVisible = true
      },
      async getAll() {
        const {
          data: { data },
        } = await getAll({ field_id: this.fieldId, pagesize: 20 })
        this.plants = data
      },
      async getCrops() {
        const {
          data: { data },
        } = await getCrops()
        this.crops = data.filter((val) => {
          return val.name !== '苜蓿'
        })
      },
      addRow() {
        this.form.cropGrowthes.push({
          stage_name: '',
          daterange: [],
          wc_max: '',
          wc_min: '',
          soil_depth: '',
          et0: 1,
          step: 1,
          kc_start: '',
          kc_end: '',
        })
      },
      deleteRow(row, idx) {
        console.log(idx)
        this.form.cropGrowthes.splice(idx, 1)
      },
      handleAdd() {
        this.form.field_id = fieldId
        this.dialogFormVisible = true
      },
      async handleEdit(row) {
        const { data } = await getOne(row.id)
        data.cropGrowthes = row.cropGrowthes.map((val) => {
          val.daterange = [val.stage_start, val.stage_end]
          return val
        })
        this.form = data
        this.dialogFormVisible = true
      },
      handleDelete(row) {
        console.log(row)
      },
      resetForm() {
        this.form = {
          field_id: '',
          crop_id: '',
          plant_year: '',
          stubble: 1,
          started_at: '',
          autocare_mode: 0,
          autopause: 0,
        }
      },
      submit(formName) {
        this.$refs[formName].validate(async (valid) => {
          if (valid) {
            if (this.form.id) {
              const { msg } = await updateOne(this.form.id, this.form)
              this.$message.success(msg)
            } else {
              const { msg } = await addOne(this.form)
              this.$message.success(msg)
            }
            this.getAll()
            this.dialogFormVisible = false
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
    },
  }
</script>

<style lang="scss" scoped></style>
